package cn.itcast.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import cn.itcast.bos.utils.MailUtils;
import cn.itcast.crm.domain.Customer;

public class CustomerAction2 extends BaseAction<Customer> {

	// 当点击获取验证码时走此方法
	@Action(value = "customer_sendSms")
	public String sendSms() throws Exception {
		// 产生一个6位数的出数字随机数
		String randomCode = RandomStringUtils.randomNumeric(6);
		// 将随机数存到session中
		ServletActionContext.getRequest().getSession()
				.setAttribute(model.getTelephone(), randomCode);
		System.out.println("验证码是：" + randomCode);
		// 制作发送信息的内容
		String msg = "尊敬的用户您好，本次获取的验证码为：" + randomCode + ",服务电话：4006184000";

		// 发送信息
		/*String result = SmsUtils
				.sendSmsByHTTP(model.getTelephone(), randomCode);*/

		// http发送信息，返回的值如果是以000开头就是发送成功
		String result ="000/%%";
		if (result.startsWith("000")) {
			System.out.println("给" + model.getTelephone() + "发送成功");
		} else {
			System.out.println("信息发送失败");
		}
		return NONE;
	}

	// 当验证码发送成功，并且各个信息都满足，发送注册请求，这时要产生一个邮箱激活码，24小时内生效
	// 属性驱动接收用户输入的验证码
	private String checkCode;

	public void setCheckCode(String checkCode) {
		this.checkCode = checkCode;
	}

	// 自动注入radis的模板
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	// 这时要用到radis，
	@Action(value = "customer_regist", results = {
			@Result(name = "success", type = "redirect", location = "signup-success.html"),
			@Result(name = "input", type = "redirect", location = "signup.html") })
	public String regist() {

		// 首先要判断你输入的验证码是否正确，获取之前存入的code
		String codeString = (String) ServletActionContext.getRequest()
				.getSession().getAttribute(model.getTelephone());

		// 进行判断
		if ("".equals(codeString) || checkCode == null
				|| !codeString.equals(checkCode)) {
			System.out.println("验证码输入错误...");
			return INPUT;
		}

		// 保存客户信息
		WebClient
				.create("http://localhost:9002/crm_management/services"
						+ "/customerService/customer")
				.type(MediaType.APPLICATION_JSON).post(model);
		// 清空验证码
		ServletActionContext.getRequest().getSession()
				.removeAttribute(model.getTelephone());
		System.out.println("注册成功");

		// 发送邮件激活

		// 产生邮件激活码
		String activeCode = RandomStringUtils.randomNumeric(32);
		// 将激活码存入到redis缓存，设置24小时失效
		redisTemplate.opsForValue().set(model.getTelephone(), activeCode, 24,
				TimeUnit.HOURS);
		// 编写邮件信息：里面传两个参数手机号和激活码，手机号是为了判断确定客户
		String content = "尊敬的客户您好，请于24小时内，进行邮箱账户的绑定，点击下面地址完成绑定:<br/><a href='"
				+ MailUtils.activeUrl + "?telephone=" + model.getTelephone()
				+ "&activecode=" + activeCode + "'>速运快递邮箱绑定地址</a>";
		MailUtils.sendMail("快递注册", content, model.getEmail());
		return SUCCESS;
	}

	// 当用户点击激活信息的时候，进入方法，进行判断激活码，进行激活
	// 属性驱动
	private String activecode;

	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	@Action("customer_activeMail")
	public String activeMail() throws IOException {
		// 解决中文乱码问题
		ServletActionContext.getResponse().setContentType(
				"text/html;charset=utf-8");
		// 从redis中获取激活码
		String activecodeRedis = redisTemplate.opsForValue().get(
				model.getTelephone());

		// 判断激活码是否有效
		if (activecodeRedis == null || activecodeRedis.equals(activecode)) {
			ServletActionContext.getResponse().getWriter()
					.println("激活码无效，请登录系统，重新绑定邮箱！");
		} else {
			// 先查询在修改，查询是否已经激活
			Customer customer = WebClient
					.create("http://localhost:9002/crm_management/services"
							+ "/customerService/customer/telephone/"
							+ model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);

			// 判断是否已经激活如果已经激活就提醒
			if (customer.getType() == null || customer.getType() != 1) {
				// 进行激活
				WebClient.create(
						"http://localhost:9002/crm_management/services"
								+ "/customerService/customer/updatetype/"
								+ model.getTelephone()).get();
				ServletActionContext.getResponse().getWriter()
						.println("邮箱绑定成功！");
			}else {
				// 已经绑定过
				ServletActionContext.getResponse().getWriter()
						.println("邮箱已经绑定过，无需重复绑定！");
			}
			//清除激活码
			redisTemplate.delete(model.getTelephone());
		}
		return NONE;
	}

}
